from lib.types import TDate

class Motor:

	def __init__(self, ws):
		self.ws = ws
		self.db = ws.db

	def run(self, parent, d):

		where = ['true']

		if d.get('cliente'):
			where.append("cl.grid='%d'" % d['cliente'])
			
		if d.get('caso'):
			where.append("c.grid='%d'" % d['caso'])
			
		sql = "select c.grid as caso_grid, cl.grid as cliente_grid, c.assunto as caso_nome, "\
			  "c.data_cadastro as caso_data, cl.nome as cliente_nome, "\
			  "t.data_cadastro as tarefa_data, t.assunto as tarefa_nome, f.nome as tarefa_funcionario, "\
			  "e.descricao as tarefa_estado from caso c join cliente cl on (cl.grid=c.cliente) "\
			  "left join cliente_tarefa ct on (ct.cliente=cl.grid) "\
			  "left join tarefa t on (t.grid=ct.tarefa) "\
			  "left join funcionario f on (f.grid=t.funcionario) "\
			  "left join estado e on (e.grid=t.estado) where %s order by cl.grid, c.grid, t.data_cadastro" % ' and '.join(where)
		rs = self.db.get_dict_result(sql)

		for r in rs:
			r['caso_data'] = TDate().parse(r['caso_data'])
			r['tarefa_data'] = TDate().parse(r['tarefa_data'])
			parent.feed(r)
